package org.summer.lawyer.service.impl;

import com.baomidou.lock.annotation.Lock4j;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.summer.lawyer.domain.SpuStats;
import org.summer.lawyer.mapper.SpuStatsMapper;
import org.summer.lawyer.service.ISpuStatsService;

/**
 *
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SpuStatsServiceImpl extends ServiceImpl<SpuStatsMapper, SpuStats> implements ISpuStatsService {


    @Lock4j(keys = "{#spuId}", acquireTimeout = 1000, expire = 10000)
    @Override
    public void updateSpuSales(Long spuId, Integer sales) {
        LambdaQueryWrapper<SpuStats> lqw = Wrappers.lambdaQuery();
        lqw.eq(SpuStats::getSpuId, spuId);
        SpuStats spuStats = baseMapper.selectOne(lqw, false);
        if (spuStats == null) {
            spuStats = new SpuStats();
            spuStats.setSpuId(spuId);
            sales = sales < 0 ? 0 : sales;
            spuStats.setTotalSales(sales);
            baseMapper.insert(spuStats);
        } else {
            Integer total = spuStats.getTotalSales() == null ? 0 : spuStats.getTotalSales();
            total = total + sales;
            spuStats.setTotalSales(total);
            baseMapper.updateById(spuStats);
        }

    }
}
